package chenji.watcher.core;

import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.entity.Player;

import chenji.watcher.Main;

public class PlayerWatchGroup {
	private int state;
	private WatchGroupTeleporter nowPlay;

	private int taskinfo;
	private Player p;
	private WatchGroupData wgd;
	private int loc;
	private boolean hasSendTeleporterTitle = false;
	private Location startLocation;

	public PlayerWatchGroup(Player p, WatchGroupData wgd) {

		this.p = p;
		p.setGameMode(GameMode.SPECTATOR);
		this.wgd = wgd;
		this.state = 0;
		this.startLocation = p.getLocation();
	}

	public void task() {
		this.taskinfo++;
		
		
		if (this.state == 0) {
			this.state = 1;
			this.playTitle(this.wgd.getStartTitle());
		}
		if (this.state == 1) {
			if (this.taskinfo >= wgd.getStartTime()) {
				this.state = 2;

				this.loc = 1;
				this.taskinfo = 0;
			}
		}
		if (this.state == 2) {
			this.playWatchGroupManager();
		}
		if (this.state == 3) {
			this.playTitle(this.wgd.getEndTitle());
			this.state = 4;
			this.taskinfo = 0;
		}
		if (this.state == 4) {
			if (this.taskinfo >= wgd.getEndTime()) {
				this.state = 5;
				Main.getWatchGroupManager().playFinish(p);
				p.teleport(this.startLocation);
				p.setGameMode(GameMode.SURVIVAL);
			}
		}

	}

	private void playWatchGroupManager() {
		if (this.nowPlay == null) {
			this.updateNowPlay();
		}
		if (!(this.hasSendTeleporterTitle)) {
			this.playTitle(this.nowPlay.getTitle());

			this.hasSendTeleporterTitle = true;
		}
		if (this.taskinfo >= this.nowPlay.getWaitTime()) {
			this.updateNowPlay();
		}
	}

	private void updateNowPlay() {
		int i = 0;
		for (WatchGroupTeleporter t : this.wgd.getTPS()) {
			i++;
			if (i == loc) {
				loc++;
				this.nowPlay = t;
				this.hasSendTeleporterTitle = false;
				this.taskinfo = 0;
				p.teleport(t.getLocation());
				return;
			}
		}
		this.state = 3;
	}

	@SuppressWarnings("deprecation")
	private void playTitle(String Title) {
		if (Title == null) {
			return;
		}
		Title = Title.replaceAll("&", "§");
		String[] s = Title.split("\\|");
		if (s.length == 1) {
			p.sendTitle(s[0], "");
		} else {
			p.sendTitle(s[0], s[1]);
		}
	}

	public void exit() {
		this.state = -1;
		if(this.wgd.canback()){
		this.p.teleport(this.startLocation);}
		p.setGameMode(GameMode.SURVIVAL);
		
	}

}
